package cn.turboinfo.fuyang.api.provider.common.component.shop.listener

import cn.turboinfo.fuyang.api.provider.common.constant.GeoConstants
import cn.turboinfo.fuyang.api.provider.common.repository.database.shop.HousekeepingShopPO
import cn.turboinfo.fuyang.api.provider.common.service.geo.GeoService
import mu.KotlinLogging
import nxcloud.foundation.core.data.support.listener.EntityLifecycleListener
import org.springframework.stereotype.Component
import org.springframework.transaction.support.TransactionSynchronization
import org.springframework.transaction.support.TransactionSynchronizationManager

@Component
class ShopGeoListener(
    private val geoService: GeoService,
) : EntityLifecycleListener {

    private val logger = KotlinLogging.logger {}
    override fun onPostPersist(entity: Any) {
        registerAfterCommitSynchronization(entity as HousekeepingShopPO)
    }

    override fun onPostUpdate(entity: Any) {
        registerAfterCommitSynchronization(entity as HousekeepingShopPO)
    }

    /**
     * 插入或者更新提交成功后维护地理信息
     */
    private fun registerAfterCommitSynchronization(entity: HousekeepingShopPO) {
        TransactionSynchronizationManager.registerSynchronization(object : TransactionSynchronization {
            override fun afterCommit() {
                if (entity.deleted > 0) {
                    logger.error {
                        "家政服务门店软删除, 移除地理信息, id=${entity.id}"
                    }
                    geoService.remove(GeoConstants.STORE_SHOP, entity.id.toString())
                } else if (entity.longitude != null && entity.latitude != null) {
                    logger.error {
                        "家政服务门店维护地理信息, id=${entity.id}, longitude=${entity.longitude}, latitude=${entity.latitude}"
                    }
                    geoService.add(
                        GeoConstants.STORE_SHOP,
                        entity.id.toString(),
                        entity.longitude.toDouble(),
                        entity.latitude.toDouble()
                    )
                }
            }
        })
    }

}